﻿using Microsoft.Extensions.Caching.Memory;
using System;
using System.Linq;

namespace RSTAi.Platform.GrpcService.Common
{
    public class CacheHelper
    {
        private static readonly object cacheLock = new();
        private static readonly MemoryCache cache = new MemoryCache(new MemoryCacheOptions());
        private static readonly int ExpirationInMinutes = 60;//缓存过期时间
        private static readonly Random random = new();
        /// <summary>
        /// 产品列表
        /// </summary>
        public const string PRODUCT_LIST = "PRODUCT_LIST";
        /// <summary>
        /// 当前产品
        /// </summary>
        public const string CURRENT_PRODUCT = "CURRENT_PRODUCT";

        /// <summary>
        /// 相机列表
        /// </summary>
        public const string CAMERA_LIST = "CAMERA_LIST";

        /// <summary>
        /// 流程列表
        /// </summary>
        public const string STEPS_LIST = "STEPS_LIST";
        /// <summary>
        /// 插入缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetCache(string key, object value)
        {
            lock (cacheLock)
            {
                object obj = new object();
                if (cache.TryGetValue(key, out obj))
                    cache.Remove(key);
                int rd = random.Next(5);
                cache.Set(key, value, TimeSpan.FromMinutes(ExpirationInMinutes + rd));
            }
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T? GetCache<T>(string key)
        {
            object obj;
            lock (cacheLock)
            {
                if (cache.TryGetValue(key, out obj))
                {
                    var cachedValue = (T)cache.Get(key);
                    return cachedValue;
                }
                else
                {
                    return default;
                }
            }
        }

        /// <summary>
        /// 清除key的缓存
        /// </summary>
        /// <param name="key"></param>
        public static void ClearCache(string key)
        {
            object obj;
            lock (cacheLock)
            {
                if (cache.TryGetValue(key, out obj))
                {
                    cache.Remove(key);
                }
            }
        }


       
    }


   







}
